<template>
	<view class="bg-white ">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="title" label="活动名" required>
				<uni-easyinput placeholder="请填写活动名" v-model="formData.title" trim="both" />
			</uni-forms-item>
			<uni-forms-item name="place" label="地点" required>
				<uni-easyinput placeholder="请填写活动地点" v-model="formData.place" trim="both" />
			</uni-forms-item>
			<uni-forms-item name="scores" label="积分数" required>
				<uni-easyinput type="number" placeholder="请填写所需积分" v-model.number="formData.scores"/>
			</uni-forms-item>
			<uni-forms-item name="tag" label="活动分类" required>
				<xfl-select 
				            :list="tagList"
				            :clearable="false"
				            :showItemNum="5" 
				            :isCanInput="true"
				            :placeholder = "'请选择分类'"
				            :selectHideType="'hideAll'"
							@change="tagChange"
				        >
				        </xfl-select>
			</uni-forms-item>
			<uni-forms-item name="date" label="活动日期" required>
				<uni-datetime-picker type="date" v-model="formData.date" start="2021-01-1" end="2025-12-31"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="starttime" label="活动时间" required>
				<uni-datetime-picker type="time" v-model="formData.starttime"></uni-datetime-picker>
			</uni-forms-item>
			<uni-forms-item name="showOnIndex" label="是否首页推荐">
				<switch @change="SwitchA" :class="formData.showOnIndex?'checked':''" :checked="formData.showOnIndex?true:false"></switch>
			</uni-forms-item>
			<uni-forms-item name="desc" label="详细描述" required>
				<uni-easyinput type="textarea" placeholder="请填写详细描述" v-model="formData.desc" trim="both" />
			</uni-forms-item>
			<view class="cu-bar bg-white margin-top solids-bottom">
				<view class="action">
					图片上传
				</view>
				<view class="action">
					{{imgList.length}}/9
				</view>
			</view>
			<view class="bg-white padding">
				<text class="gray">第一张图为活动目录图片, 尺寸要求：长宽比2:1。</text>
			</view>
			<view class="cu-form-group padding">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
						<image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<9">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
			<view class="flex justify-between padding">
				<button type="primary" size="mini" @click="submit">提交</button>
				<button size="mini" @click="navigateBack">返回</button>
			</view>
			
		</uni-forms>
	</view>
</template>

<script>
	import upFile from '@/common/uploadUtils.js'

	const app = getApp();
	const db = uniCloud.database();
	const dbCollectionName = "activities"
	
	export default {
		data() {
			return {
				formData: {
					"title": "",
					"scores": 0,
					"starttime": '12:01:00',
					"date": "2021-01-01",
					"place": "",
					"showOnIndex": false,
					"desc": "",
					"imgPath": [],
					"tag": ""
				},
				tagList: ["燕巢录", "党建活动","讲座","其他"],
				imgList: [],
				userInfo: null
			};
		},

		onLoad() {
			// 检查用户信息是否完整
		},


		methods: {
			SwitchA(e) {
				this.formData.showOnIndex = e.detail.value
			},
			
			tagChange(e) {
				this.formData.tag = e.newVal;
			},
			
			navigateBack(e) {
				uni.navigateBack({
					delta: 1
				})
			},

			ChooseImage(e) {
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
						
					}
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					content: '确定要删除这张照片吗？',
					cancelText: '再看看',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			textareaInput(e) {
				this.desc = e.detail.value
			},
			// 提交活动申请
			submit: function(value) {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.submit().then((res) => {
					this.submitForm(res)
				}).catch((errors) => {
					uni.hideLoading()
				})
			},
			submitForm(value) {
				var file_path = new Array();
				var value = value;
				var that = this;
				upFile.mutiupload(this.imgList, file_path ,0, this.imgList.length, value.title, function(file_path) {
					value["imgPath"] = file_path;
					// 使用 clientDB 提交数据
					db.collection(dbCollectionName).add(value).then((res) => {
						uni.showToast({
							title: '新增成功'
						})
						that.getOpenerEventChannel().emit('refreshData')
						setTimeout(() => uni.navigateBack(), 500)
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						uni.hideLoading()
					})
				})
			},
		}
	}
</script>

<style>
	@import "@/colorui/main.css";
	@import "@/colorui/icon.css";
	.cu-form-group .title {
		min-width: calc(4em + 15px);
	}
</style>
